#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<string.h>

#define NUM 64
#define CMD_NUM 128

int main()
{
  while(1)
  {
    char command[NUM] = {0};
    char* argv[CMD_NUM] = {NULL};
    //1.打印提示符
    printf("[who@minishell]# ");
    fflush(stdout);
    //获取命令符
    fgets(command,NUM,stdin);
    command[strlen(command)-1] = '\0';//这一行代码消除最后的回车字符
    //3.解析命令行
    const char* sep = " ";
    argv[0] = strtok(command,sep);
    int i = 1;
    while(argv[i] = strtok(NULL,sep))
    {
      i++;
    }
    //4.检测命令是否需要shell本身执行，内建命令
    if(strcmp(argv[0],"cd")==0)
    {
      if(argv[1])
        chdir(argv[1]);
      continue;
    }
    //5.执行命令
    if(fork() == 0)
    {
      execvp(argv[0],argv);
      exit(1);
    }
    waitpid(-1,NULL,0);
    printf("执行命令成功！\n");

  }
  return 0;
}
